<script setup lang='ts'>
import { getEditBlog, setAddBlog } from '@/api/blog';
import { showFailToast, showToast } from 'vant';
import { showLoadingToast } from 'vant/es';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter()
// 图片
const fileList = ref([])
const title = ref('')
const contentText = ref('')

// 图片大小超出
const oversize = () => {
  showFailToast('单个图片不能超出20MB')
}

// 提交博文
const postBlog = async () => {
 
  if(title.value == ''){
    showFailToast('请输入标题')
    
    return
  }
  if(contentText.value == ''){
    showFailToast('请输入正文')
    return
  }
  // 是否为更新
  if(blogId.value){
   let formData = new FormData();
        formData.append("id", blogId.value)
        const imgStr = []
        for (let i = 0; i < fileList.value.length; i++) {
            if (fileList.value[i].url) {
                imgStr.push(fileList.value[i].url)
            } else {
                formData.append("images", fileList.value[i].file)
            }
        }
        let finalImgStr = imgStr.join(",");
        formData.append("imgStr", finalImgStr)
    formData.append('title',title.value)
    formData.append('content',contentText.value)
    const loading = ref(true)
    showLoadingToast({
      message: '更新中...',
      forbidClick: loading.value,
      loadingType: 'spinner',
    });
    const res = await getEditBlog(formData)
    loading.value = false
    if(res.data.code === 0){
      showToast('更新成功')
      router.replace("/blog/detail?id=" + blogId.value)
    }else {
      showToast('更新失败'+res.data.description)
    }
    return
  }
  let formData = new FormData()
  for(let i = 0; i < fileList.value.length ;i++){
    formData.append('images',fileList.value[i].file)
  }
  formData.append('title',title.value)
  formData.append('content',contentText.value)
  const loading = ref(true)
  showLoadingToast({
    message: '发布中...',
    forbidClick: loading.value,
    loadingType: 'spinner',
  });
  const res = await setAddBlog(formData)
  loading.value = false
  if(res.data.code === 0){
    showToast('发布成功')
    router.replace('/')
  }else {
    showToast('发布失败'+res.data.description)
  }
  

}
const route = useRoute()
const blogId = ref()
onMounted(() => {
  if (route.query.id) {
        blogId.value = route.query.id
    }
    if (route.query.images) {
        route.query.images.forEach((item: any) => {
            const image = {
                url: item,
                isImage: true
            }
            fileList.value.push(image)
        })
    }
    if (route.query.title) {
        title.value = route.query.title
    }
    if (route.query.content) {
        contentText.value = route.query.content
    }
})
</script>
<template>
  <van-sticky>
    <van-nav-bar title="编写博文" @click-left="$router.replace('/')" @click-right="postBlog"  left-arrow>
      <template #right>
        发布
      </template>
    </van-nav-bar>
  </van-sticky>
  <div class="content">
    <van-uploader v-model="fileList" @oversize="oversize" multiple :max-count="5" preview-size="100px" :max-size="20 * 1024 * 1024"/>

    <van-cell-group inset>
      <van-field v-model="title" placeholder="请输入标题" maxlength="20" show-word-limit/>
      <van-field 
        v-model="contentText" 
        placeholder="添加正文" 
        rows="5"
        autosize
        maxlength="1000"
        show-word-limit
        type="textarea"
      />
    </van-cell-group>
  </div>
</template>
<style scoped >
.content{
  margin: 5px 10px;
}
</style>
